package com.xhwl.logistics.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Strings;
import com.xhwl.common.dto.cent.eesd.EnvStatisticsReqDTO;
import com.xhwl.common.dto.cent.eesd.EnvStatisticsReqV2DTO;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.bi.DwdDimChargeMetrics;
import com.xhwl.logistics.bo.VehicleParkingLotSecondBO;
import com.xhwl.logistics.bo.cent.ProjectBO;
import com.xhwl.logistics.bo.input.QueryVehicleAccessRecordThirdBO;
import com.xhwl.logistics.converter.mapstruct.VehicleExcelConverter;
import com.xhwl.logistics.dao.VehcCarRecordDao;
import com.xhwl.logistics.dto.query.VehicleAccessRecordExcelDTO;
import com.xhwl.logistics.entity.excel.VehicleAccessReportFormsBiExcel;
import com.xhwl.logistics.service.business.VehicleExcelBusinessService;
import com.xhwl.logistics.service.cent.IBIVehicleService;
import com.xhwl.logistics.service.cent.QueryProjectService;
import com.xhwl.logistics.service.impl.VehicleParkingLotServiceImpl;
import com.xhwl.logistics.vo.AccessRecordQuery;
import com.xhwl.logistics.vo.AccessRecordStatisticsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

//@RestController
public class VehicleExcelController {

    @Autowired
    private VehicleExcelBusinessService vehicleExcelBusinessService;

    @Autowired
    private VehicleParkingLotServiceImpl vehicleParkingLotService;

    @Autowired
    private VehicleExcelConverter vehicleExcelConverter;

    @Autowired
    private VehcCarRecordDao vehcCarRecordDao;

    @Autowired
    private IBIVehicleService ibiVehicleService;

    @Autowired
    private QueryProjectService queryProjectService;

    @GetMapping("access-record/excel")
    public void excelForAccessRecord(HttpServletResponse httpServletResponse, @Valid VehicleAccessRecordExcelDTO vehicleAccessRecordExcelDTO) {
        String parkingLotName = vehicleAccessRecordExcelDTO.getParkingLotName();

        QueryVehicleAccessRecordThirdBO queryVehicleAccessRecordThirdBO;
        if (Strings.isNullOrEmpty(parkingLotName)) {
            queryVehicleAccessRecordThirdBO = vehicleExcelConverter.toQueryVehicleAccessRecordThirdBO(vehicleAccessRecordExcelDTO, null);
        } else {
            VehicleParkingLotSecondBO vehicleParkingLotSecondBO = vehicleParkingLotService.queryParkingLot(vehicleAccessRecordExcelDTO.getProjectId(), parkingLotName);
            queryVehicleAccessRecordThirdBO = vehicleExcelConverter.toQueryVehicleAccessRecordThirdBO(vehicleAccessRecordExcelDTO, vehicleParkingLotSecondBO.getParkId());
        }

        ServletOutputStream outputStream;
        try {
            outputStream = httpServletResponse.getOutputStream();
        } catch (IOException e) {
            throw new BusinessException("获取输出流异常");
        }

        String fileName;
        try {
            fileName = URLEncoder.encode("车辆进出记录.xlsx", StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            throw new BusinessException("URL编码文件名出现异常");
        }

        httpServletResponse.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + fileName);
        vehicleExcelBusinessService.accessRecord(outputStream, queryVehicleAccessRecordThirdBO);
    }


    @GetMapping("access-record/report-forms-bi")
    public void reportFormsForAccessBiRecord(HttpServletResponse httpServletResponse, @Valid EnvStatisticsReqDTO envStatisticsReqDTO, @Valid AccessRecordQuery query) {

        ProjectBO projectBO = queryProjectService.queryProject(envStatisticsReqDTO.getProjectId());

        query.setPageNumber(0);
        query.setPageSize(Integer.MAX_VALUE);
        IPage<AccessRecordStatisticsVo> recordStatisticsVoIPage = vehcCarRecordDao.queryRecordStatistics(query.toPage(), query);

        ServletOutputStream outputStream;
        try {
            outputStream = httpServletResponse.getOutputStream();
        } catch (IOException e) {
            throw new BusinessException("获取输出流异常");
        }

        String fileName;
        try {
            fileName = URLEncoder.encode("车辆进出统计.xlsx", StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            throw new BusinessException("URL编码文件名出现异常");
        }
        httpServletResponse.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + fileName);

        EnvStatisticsReqV2DTO dto = new EnvStatisticsReqV2DTO();
        dto.setProjectId(query.getProjectId());
        dto.setDate(query.getDate());
//        dto.setProjectName(projectBO.getProjectName());
//        dto.setPageNumber(1);
//        dto.setPageSize(999);


        if (query.getMode() == null || query.getMode() == 0) {
            dto.setTimeRange("TOTAL");
        } else if (query.getMode() == 1) {
            dto.setTimeRange("month");
        } else if (query.getMode() == 2) {
            dto.setTimeRange("year");
        } else {
            throw new IllegalArgumentException("mode参数非法");
        }

        ResultJson<Page<DwdDimChargeMetrics>> resultJson = ibiVehicleService.chargeTrendV2(dto);

        List<VehicleAccessReportFormsBiExcel> vehicleAccessReportFormsBiExcels = new ArrayList<>();
        if (recordStatisticsVoIPage != null && recordStatisticsVoIPage.getRecords() != null) {
            recordStatisticsVoIPage.getRecords().forEach(it -> {
                VehicleAccessReportFormsBiExcel vehicleAccessReportFormsBiExcel = new VehicleAccessReportFormsBiExcel();
                vehicleAccessReportFormsBiExcel.setDate(it.getEnterDate() == null ?  it.getExistDate() : it.getEnterDate());
                vehicleAccessReportFormsBiExcel.setProjectName(projectBO.getProjectName());
                vehicleAccessReportFormsBiExcel.setCarInCount(it.getInTypeCount() == null ? 0 : it.getInTypeCount());
                vehicleAccessReportFormsBiExcel.setCarOutCount(it.getOutTypeCount() == null ? 0 : it.getOutTypeCount());
                vehicleAccessReportFormsBiExcel.setCarInOutCount(vehicleAccessReportFormsBiExcel.getCarInCount() + vehicleAccessReportFormsBiExcel.getCarOutCount());
                vehicleAccessReportFormsBiExcel.setLimitTimeInOutCount((it.getInLimitTimeCardCount() == null ? 0 : it.getInLimitTimeCardCount()) + (it.getOutLimitTimeCardCount() == null ? 0 : it.getOutLimitTimeCardCount()));
                vehicleAccessReportFormsBiExcel.setFullTimeInOutCount((it.getInFullTimeCardCount() == null ? 0 : it.getInFullTimeCardCount()) + (it.getOutFullTimeCardCount() == null ? 0 : it.getOutFullTimeCardCount()));
                vehicleAccessReportFormsBiExcel.setTempCarInOutCount((it.getInTempCardCount() == null ? 0 : it.getInTempCardCount()) + (it.getOutTempCardCount() == null ? 0 : it.getOutTempCardCount()));
                vehicleAccessReportFormsBiExcel.setTramCarInOutCount(0);
                if (resultJson != null && resultJson.getResult() != null && resultJson.getResult().getRecords() != null) {
                    resultJson.getResult().getRecords().stream().filter(dwdDimChargeMetrics -> {
                        return dwdDimChargeMetrics.getDt().equals(vehicleAccessReportFormsBiExcel.getDate());
                    }).findFirst().ifPresent(value -> {
                        vehicleAccessReportFormsBiExcel.setTramCarInOutCount(value.getConnectorA());
                    });
                }
                vehicleAccessReportFormsBiExcels.add(vehicleAccessReportFormsBiExcel);
            });
        }

        vehicleExcelBusinessService.accessReportFormsBi(outputStream, vehicleAccessReportFormsBiExcels);
    }
}
